<?php

namespace App\Http\Controllers\Admin;

use App\Models\CompetiteActivity;
use App\Models\CompetiteActivityWorks;
use App\Models\CompetiteActivityTag;
use App\Models\Manage;
use App\Validate\CompetiteActivityValidate;
use Illuminate\Support\Facades\DB;

/**
 * 线上大赛活动
 * Class CompetiteActivity
 * @package app\admin\controller
 */
class CompetiteActivityController extends CommonController
{
    public $model = null;
    public $validate = null;
    public $worksModel = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new CompetiteActivity();
        $this->validate = new CompetiteActivityValidate();
        $this->worksModel = new CompetiteActivityWorks();
    }


    /**
     * 获取报名参数
     */
    public function getCompetiteActivityApplyParam()
    {
        $data = $this->model->getCompetiteActivityApplyParam();
        return $this->returnApi(200, "获取成功", true, $data);
    }

    /**
     * 类型(用于下拉框选择)
     */
    public function filterList()
    {

        $condition[] = ['is_del', '=', 1];

        return $this->model->getFilterList(['id', 'title'], $condition);
    }

    /**
     * 列表
     * @param page int 当前页
     * @param limit int 分页大小
     * @param type_id string 类型id
     * @param is_play int 是否发布 1.发布 2.未发布    默认1
     * @param keywords string 搜索关键词(文章标题)
     * @param start_time datetime 比赛开始时间(开始)
     * @param end_time datetime 比赛开始时间(截止)
     */
    public function lists()
    {
        $page = request()->page ? intval(request()->page) : 1;
        $limit = request()->limit ? intval(request()->limit) : 10;
        $type_id = request()->type_id;
        $is_play = request()->is_play;
        $keywords = request()->keywords;
        $start_time = request()->start_time;
        $end_time = request()->end_time;

        $res = $this->model->lists(null, $type_id, $keywords, $start_time, $end_time, null, null, $is_play, $limit);

        if (empty($res['data'])) {
            return $this->returnApi(203, '暂无数据');
        }

        foreach ($res['data'] as $key => $val) {
            $res['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);
            $res['data'][$key]['unlook_num'] = $this->worksModel->getUnLookNumber($val['id']);
            $res['data'][$key]['uncheck_num'] = $this->worksModel->getUnCheckNumber($val['id']);


            $res['data'][$key]['type_tag'] = CompetiteActivityTag::getTagNameByTagId($val['tag_id']);
            $res['data'][$key]['type_name'] = !empty($val['con_type']['type_name']) ?  $val['con_type']['type_name'] : '';
            $res['data'][$key]['manage_name'] = Manage::getManageNameByManageId($val['manage_id']);
            unset($res['data'][$key]['con_type']);
        }

        $res = $this->disPageData($res);
        //   $res['data'] = $this->addSerialNumber($res['data']);
        return $this->returnApi(200, "查询成功", true, $res);
    }

    /**
     * 详情
     * @param id int 比赛id
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $res = $this->model->detail($this->request->id);

        if (empty($res)) {
            return $this->returnApi(202, '参数传递错误');
        }

        $res['tag_name'] = CompetiteActivityTag::getTagNameByTagId($res->tag_id); //获取活动标签

        $real_info_array = $this->model->getCompetiteActivityApplyParam();
        $res->real_info_value = $this->getRealInfoArray($res->real_info, $real_info_array, 'value');
        $res->real_info_value = join("|", $res->real_info_value);

        $res->word_num = $this->worksModel->where('con_id', $this->request->id)->where('status', 1)->count();
        // $user_num = $this->worksModel->where('con_id', $this->request->id)->groupBy('user_id')->get(); //人次
        // $res->user_num = count($user_num); //人次

        $res->user_num = $this->worksModel->getTakeNumber($this->request->id); //人次


        $res->all_vote_num = $this->worksModel->where('con_id', $this->request->id)->sum('vote_num'); //总投票量
        $res->all_browse_num = $this->worksModel->where('con_id', $this->request->id)->sum('browse_num'); //总浏览量
        $res->all_word_num = $this->worksModel->where('con_id', $this->request->id)->whereIn('status', [1, 2, 3])->count();
        $res->approval_word_num = $this->worksModel->where('con_id', $this->request->id)->whereIn('status', [1, 2])->count();
        $res->unapproval_word_num = $this->worksModel->where('con_id', $this->request->id)->where('status', '=', 3)->count();

        //判断是否可以更改是否需要绑定读者证，有人预约就不允许修改
        $apply_status = $this->worksModel->actIsApply($this->request->id);
        $res['is_can_is_reader'] = $apply_status ? false : true; //false 有人报名，不允许修改

        $res['check_manage_id'] = $res['check_manage_id'] ? explode(',', $res['check_manage_id']) : null;


        $res->type_name = !empty($res->conType['type_name']) ?  $res->conType['type_name'] : '';
        unset($res->conType);
        return $this->returnApi(200, "查询成功", true, $res->toArray());
    }

    /**
     * 新增
     * @param title string 名称
     * @param type_id int 活动类型
     * @param tag_id int 活动标签  多个 逗号 拼接
     * @param img string 活动封面
     * @param host_handle string 主办单位
     * @param con_start_time datetime 投稿开始时间
     * @param con_end_time datetime 投稿结束时间
     * @param vote_start_time datetime 投票开始时间
     * @param vote_end_time datetime 投票结束时间
     * @param tel string 电话号码 (咨询电话)
     * @param contacts string 联系人
     * @param vote_way int 投票方式   1  总票数方式   2 每次投票方式
     * @param is_reader int 报名是否需要绑定读者证   1.是   2.否(默认）
     * @param number int 票数
     * @param originals text 原创申明 
     * @param promise text 作者承诺
     * @param intro text 简介
     * @param rule_content text 活动规则|活动内容
     * @param deliver_way int 投递方式  1 全部  2 前端用户自己上传  3 团队账号上传
     * @param check_manage_id int 审核管理员id，多个，逗号拼接，逐个审评，一旦有人上传作品，则不能更改审核人  
     * @param appraise_way int 评选方式  1、全部  2、用户投票  3 专家评选 
     * 
     * @param real_info text 需要验证的真实信息id用|连接起来    1、作者   2 、身份证号码  3、电话号码   4、读者证号    5、微信号 6、单位名称 7、指导老师  8、指导老师联系方式  9 年龄 10 学校  11 参赛者 12 原著
     * @param is_need_authorizations text 是否需要授权书 1 是 2 否
     * @param is_need_promise text 是否需要承诺书 1 是 2 否
     */
    public function add()
    {
        if (!$this->validate->scene('add')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }

        if ($this->request->appraise_way != 3 && (empty($this->request->number) || $this->request->number > 100)) {
            return $this->returnApi(202, "投票量不能超过100");
        }
        $is_exists = $this->model->nameIsExists($this->request->title, 'title');

        if ($is_exists) {
            return $this->returnApi(202, "该标题已存在");
        }

        DB::beginTransaction();
        try {
            $data = $this->request->all();
            $data['deliver_way'] = $this->request->deliver_way ? $this->request->deliver_way : 1;
            $data['app_img'] = $this->request->img;
            $data['manage_id'] = request()->manage_id;
            unset($data['img']);
            //不需要投票，去掉投票时间
            if ($data['appraise_way'] == 3) {
                $data['vote_start_time'] = null;
                $data['vote_end_time'] = null;
            }

            $this->model->add($data);

            DB::commit();
            return $this->returnApi(200, "新增成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, "新增失败" . $e->getMessage() . $e->getFile() . $e->getLine());
        }
    }

    /**
     * 编辑
     * @param id int 图书馆id
     * @param title string 名称
     * @param type_id int 活动类型
     * @param tag_id int 活动标签  多个 逗号 拼接
     * @param img string 活动封面
     * @param host_handle string 主办单位
     * @param con_start_time datetime 投稿开始时间
     * @param con_end_time datetime 投稿结束时间
     * @param vote_start_time datetime 投票开始时间
     * @param vote_end_time datetime 投票结束时间
     * @param tel string 电话号码 (咨询电话)
     * @param contacts string 联系人
     * @param vote_way int 投票方式   1  总票数方式   2 每次投票方式
     * @param is_reader int 报名是否需要绑定读者证   1.是   2.否(默认）
     * @param number int 票数
     * @param originals text 原创申明 总配置  在每个馆也可单独设置    在单位哪里设置
     * @param promise text 作者承诺
     * @param intro text 简介
     * @param rule_content text 活动规则|活动内容
     * @param deliver_way int 投递方式  1 全部  2 前端用户自己上传  3 团队账号上传
     * @param check_manage_id int 审核管理员id，多个，逗号拼接，逐个审评，一旦有人上传作品，则不能更改审核人  
     * @param appraise_way int 评选方式  1、全部  2、用户投票  3 专家评选 
     * 
     * @param real_info text 需要验证的真实信息id用|连接起来    1、作者   2 、身份证号码  3、电话号码   4、读者证号    5、微信号 6、单位名称 7、指导老师  8、指导老师联系方式  9 年龄 10 学校  11 参赛者 12 原著
     * @param is_need_authorizations text 是否需要授权书 1 是 2 否
     * @param is_need_promise text 是否需要承诺书 1 是 2 否
     */
    public function change()
    {
        if (!$this->validate->scene('change')->check($this->request->all())) {
            return $this->returnApi(201, $this->validate->getError());
        }

        if ($this->request->appraise_way != 3 && (empty($this->request->number) || $this->request->number > 100)) {
            return $this->returnApi(202, "投票量不能超过100");
        }

        $is_exists = $this->model->nameIsExists($this->request->title, 'title', $this->request->id);

        if ($is_exists) {
            return $this->returnApi(202, "该标题已存在");
        }

        $res = $this->model->where('is_del', 1)->find($this->request->id);

        if (!$res) {
            $this->returnApi(201, "参数传递错误");
        }

        if ($res->is_play == 1) {
            return $this->returnApi(201, "请先撤销，在进行修改！");
        }
        //自己创建的活动，只能自己修改，负责，在审核管理员位置会有权限问题，管理员对不上
        if (request()->manage_id != 1 && request()->manage_id != $res->manage_id) {
            return $this->returnApi(201, "您无权修改此数据！");
        }

        $old_img = $res->app_img;
        if ($this->request->node && $res->node != $this->request->node) {
            return $this->returnApi(201, "举办方式不能修改");
        }

        //已有用户参加，不允许修改
        if ($res->is_reader !=  $this->request->is_reader || $res->check_manage_id !=  $this->request->check_manage_id) {
            //判断是否有人报名
            $apply_status = $this->worksModel->actIsApply($this->request->id);
            if ($apply_status && $res->is_reader !=  $this->request->is_reader) {
                return $this->returnApi(201, "已有用户参加，不能修改是否需要绑定读者证参数");
            }
            if ($apply_status && $res->check_manage_id !=  $this->request->check_manage_id) {
                $check_manage_id_diff = array_diff_key(explode(',', $res->check_manage_id), explode(',', $this->request->check_manage_id));
                //如果是取消已被系统删除的管理员，则可以去掉
                if (Manage::whereIn('id', $check_manage_id_diff)->where('is_del', 1)->first()) {
                    return $this->returnApi(201, "已有用户参加，不能修改审核管理员");
                }
            }
        }

        if ($this->request->vote != $res->vote || $this->request->vote_way != $res->vote_way) {
            //判断是否有人投票
            $vote_num = $this->worksModel->actIsVote($this->request->id);
            if ($vote_num) {
                return $this->returnApi(201, "已有用户投票，不能修改票数和投票方式");
            }
        }

        DB::beginTransaction();
        try {
            $data = $this->request->all();
            $data['deliver_way'] = $this->request->deliver_way ? $this->request->deliver_way : 1;
            $data['app_img'] = $this->request->img;
            unset($data['img']);

            //不需要投票，去掉投票时间
            if ($data['appraise_way'] == 3) {
                $data['vote_start_time'] = null;
                $data['vote_end_time'] = null;
            }
            $this->model->change($data);

            if ($old_img != $this->request->img) {
                $this->deleteFile($old_img);
            }

            DB::commit();
            return $this->returnApi(200, "修改成功", true);
        } catch (\Exception $e) {

            DB::rollBack();
            return $this->returnApi(202, "修改失败");
        }
    }

    /**
     * 删除
     * @param id int 比赛id
     */
    public function del()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('del')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $apply_status = $this->worksModel->actIsApply($this->request->id);
        if ($apply_status) {
            return $this->returnApi(201, "已有用户参加，不能删除此活动");
        }

        $res = $this->model->del($this->request->id);

        if ($res === true) {
            return $this->returnApi(200, "删除成功", true);
        }
        return $this->returnApi(202, $res);
    }


    /**
     * 发布与取消发布
     * @param ids 书籍id，多个用逗号拼接   all 是，其余字符  ids 必传
     * @param is_play 是否发布  1.发布  2.未发布  默认2
     */
    public function playAndCancel()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('play_and_cancel')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        list($code, $msg) = $this->model->resumeAndCancel($this->request->ids, 'is_play', $this->request->is_play);

        $is_play = $this->request->is_play == 1 ? '发布' : '取消发布';
        if ($code === 200) {
            return $this->returnApi(200, $is_play . $msg, true);
        }
        return $this->returnApi($code, $is_play . $msg);
    }
}
